//
//  UserInfoViewController.m
//  TuiTe
//
//  Created by 张 霄鹤 on 10-4-27.
//  Copyright 2010 xhzhang. All rights reserved.
//

#import "UserInfoViewController.h"
#import "TwitterClient.h"
#import "Tweet.h"
#import "ViewControllerChooser.h"
#import "ProfileImageProcesser.h"

@implementation UserInfoViewController

@synthesize username;
@synthesize user;

@synthesize profileImage;
@synthesize lblName;
@synthesize lblScreenName;
@synthesize lblLocation;
@synthesize lblLink;
@synthesize lblDescription;
@synthesize tb;

/*
 // The designated initializer.  Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {
        // Custom initialization
    }
    return self;
}
*/

/*
// Implement loadView to create a view hierarchy programmatically, without using a nib.
- (void)loadView {
}
*/


// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
    [super viewDidLoad];
}

- (void)viewDidAppear:(BOOL)animated{
	[super viewDidAppear:animated];
	// [self.navigationController setNavigationBarHidden:NO animated:NO];
	if(self.user){
		self.navigationItem.title = self.user.name;
		[self refreshInfo];
	}else{
		if(self.username){
			self.tabBarController.navigationItem.title = self.username;
			[NSThread detachNewThreadSelector:@selector(getUserInfoFromServ:) toTarget:self withObject:self.username];
		}else{
			self.tabBarController.navigationItem.title = @"Information";
		}
	}
}

- (void)viewDidDisappear:(BOOL)animated{
	[super viewDidDisappear:animated];
	self.user = nil;
	self.username = nil;
}

/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/

- (void)didReceiveMemoryWarning {
	// Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
	
	// Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
	// Release any retained subviews of the main view.
	// e.g. self.myOutlet = nil;
	self.profileImage = nil;
	self.lblName = nil;
	self.lblScreenName = nil;
	self.lblLocation = nil;
	self.lblLink = nil;
	self.lblDescription = nil;
	self.tb = nil;
}

- (void)getUserInfoFromServ:(NSString *)uname{
	TwitterClient *tc = [TwitterClient getInstance];
	id obj = [tc doUserShow:uname];
	if (obj) {
		if ([obj isKindOfClass:[User1 class]]) {
			self.user = (User1 *)obj;
			self.username = nil;
			// TODO 此处解析出User1对象，然后进行主线程数据刷新
			[self performSelectorOnMainThread:@selector(refreshInfo) withObject:nil waitUntilDone:NO];
		}
	}
}

#pragma mark Table view methods

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 2;
}


// Customize the number of rows in the table view.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    NSInteger ret = 0;
	switch (section) {
		case 0:
			ret = 4;
			break;
		case 1:
			ret = 1;
			break;

		default:
			break;
	}
	return ret;
}


// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString *CellIdentifier = @"Cell";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];		
	}
    
    // Set up the cell...
	NSInteger row = indexPath.row;
	NSInteger section = indexPath.section;
	
	NSString *tt = @"";
	
	if (section == 0) {
		if (user) {
			switch (row) {
				case 0:
					tt = [NSString stringWithFormat:@"%d %@",user.favourites_count,@"Favorite"];
					break;
				case 1:
					tt = [NSString stringWithFormat:@"%d %@",user.friends_count,@"Following"];
					break;
				case 2:
					tt = [NSString stringWithFormat:@"%d %@",user.followers_count,@"Followers"];
					break;
				case 3:
					tt = @"Lists";
					break;
				default:
					break;
			}
		}
		cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
	}else if (section == 1) {
		if (user) {
			if (user.following) {
				tt = @"Unfollow";
			}else {
				tt = @"Follow";
			}
			tt = [NSString stringWithFormat:@"%@ @%@",tt,user.screen_name];
		}else {
			tt = @"Waiting";
		}
	}
	cell.textLabel.text = tt;
	
    return cell;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    // Navigation logic may go here. Create and push another view controller.
	// AnotherViewController *anotherViewController = [[AnotherViewController alloc] initWithNibName:@"AnotherView" bundle:nil];
	// [self.navigationController pushViewController:anotherViewController];
	// [anotherViewController release];
	
	NSInteger row = indexPath.row;
	NSInteger section = indexPath.section;
	[tableView deselectRowAtIndexPath:indexPath animated:NO];
	if (section == 0) {
		// TODO list user info
	}else if (section == 1) {
		if (user) {
			if (user.following) {
				// TODO Unfollow
			}else {
				// TODO Follow
				[NSThread detachNewThreadSelector:@selector(followUser:) toTarget:self withObject:user.uid];
			}

		}
	}

	
}

//- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
//	CGFloat ret = 60.0;
//	NSInteger section = indexPath.section;
//	if(section == 0){
//		//NSInteger row = indexPath.r
//	}
//	return ret;
//}



// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}



// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source	
    }   
    else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}



/*
 // Override to support rearranging the table view.
 - (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
 }
 */


/*
 // Override to support conditional rearranging of the table view.
 - (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
 // Return NO if you do not want the item to be re-orderable.
 return YES;
 }
 */

#pragma mark -
#pragma mark RefreshInfo


- (void)refreshInfo{
	if (self.user) {
		self.navigationItem.title = self.user.name;
		self.lblName.text = self.user.name;
		NSString *ss = [[NSString alloc] initWithFormat:@"@%@",self.user.screen_name];
		self.lblScreenName.text = ss;
		[ss release];
		self.lblLocation.text = self.user.location;
		self.lblLink.text = self.user.url;
		self.lblDescription.text = self.user.udescription;
		[self.tb reloadData];
		
		ProfileImageProcesser *pp = [ProfileImageProcesser getInstance];
		NSString *img = self.user.profile_image_url;
		pp.delegate = self;
		if(img){			
			UIImage *im = [pp getImage:img];
			if(im){
				profileImage.image = im;
			}else{
				profileImage.image = pp.deflogo;
				[pp loadImage:img];
			}
		}
	}
}

#pragma mark -
#pragma mark ImageLoad
- (void)imageDidLoadFinished:(NSString *)imgURL{
	[self refreshInfo];
}

#pragma mark -
#pragma mark User Follow & Unfollow

- (void)followUser:(NSString *)uid{
	if (uid) {
		TwitterClient *client = [TwitterClient getInstance];
		id uobj = [client doFriendShipCreate:uid];
		if (uobj) {
			NSLog(@"Follow OK");
		}else {
			NSLog(@"Follow Error");
		}

	}
}

- (void)unfollowUser:(NSString *)uid{

}

#pragma mark -
#pragma mark MemoryManage

- (void)dealloc {
	[profileImage release];
	[lblName release];
	[lblScreenName release];
	[lblLocation release];
	[lblLink release];
	[lblDescription release];
	[tb release];
    [super dealloc];
}


@end
